<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="130px">
    <!-- 代理商信息 -->
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span class="theme">代理商信息</span>
      </div>
      <section>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="代理商姓名" prop="agents_name">
              <span v-if="$route.query.type == 'detail' || $route.query.type == 'verify'">{{
                form.agents_name
              }}</span>
              <el-input v-else v-model="form.agents_name" :disabled="disabled || editDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话" prop="phone">
              <span v-if="$route.query.type == 'detail' || $route.query.type == 'verify'">{{
                form.phone
              }}</span>
              <el-input v-else v-model="form.phone" :disabled="disabled || editDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在省市区" prop="regionids">
              <span v-if="$route.query.type == 'detail' || $route.query.type == 'verify'">{{
                form.regions.join('/')
              }}</span>
              <el-cascader
                v-else
                v-model="form.regionids"
                style="width: 100%"
                :options="AreaJson"
                clearable
                :props="{ value: 'value', label: 'label', children: 'children' }"
                :disabled="disabled"
                @change="regionChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详细地址" prop="address">
              <span v-if="$route.query.type == 'detail' || $route.query.type == 'verify'">{{
                form.address
              }}</span>
              <el-input v-else v-model="form.address" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="代理商入驻费" prop="terms">
              <span v-if="$route.query.type == 'detail' || $route.query.type == 'verify'">{{
                form.terms
              }}</span>
              <el-input v-else v-model="form.terms" :disabled="disabled || editDisabled" >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属招募人" prop="recruitment">
              <span v-if="$route.query.type == 'detail' || $route.query.type == 'verify'">{{
                form.recruitment
              }}</span>
              <el-input v-else v-model="form.recruitment" :disabled="disabled || editDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工号" prop="jobs">
              <span v-if="$route.query.type == 'detail' || $route.query.type == 'verify'">{{
                form.jobs
              }}</span>
              <el-input v-else v-model="form.jobs" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="银行卡号" prop="card_number">
              <span v-if="$route.query.type == 'detail' || $route.query.type == 'verify'">{{
                form.card_number
              }}</span>
              <el-input v-else v-model="form.card_number" :disabled="disabled" placeholder="银行卡号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="银行卡所属银行" prop="code">
              <span v-if="$route.query.type == 'detail' || $route.query.type == 'verify'">{{
                form.bank_name
              }}</span>
              <el-autocomplete
                v-else
                v-model="form.bank_name"
                style="width: 100%"
                prefix-icon="el-icon-search"
                class="inline-input"
                :fetch-suggestions="querySearch"
                placeholder="请输入选择内容"
                @select="handleSelectBank"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </section>
    </el-card>
    <!-- 按钮 -->
    <template
      v-if="
        $route.query.type == 'edit' ||
        ($route.query.type == 'add' && $store.getters.login_type != 'merchant')
      "
    >
      <el-form-item label-width="0px" style="text-align: center; margin-top: 60px">
        <el-button type="primary" style="padding: 10px 50px" @click="submitFn('form')" :disabled="isSub">
          保存
        </el-button>
      </el-form-item>
    </template>
  </el-form>
</template>

<script>
import { MaxRules, requiredRules } from '@/view/base/setting/dealer/tools'
import { addTheAgent, getArea, getTheAgent, updateTheAgent } from '@/api/agent.js'

export default {
  props: ['props_type'],
  data() {
    return {
      isEditCheckBox: false, //编辑状态是否弹窗 离开页面丢失数据
      // ---------
      AreaJson: [],
      disabled: false,
      editDisabled: false,
      // 脱敏
      datapass_block: 0,
      form: {
        agents_name: '',
        phone: '',
        regionids: [],
        regions: [],
        terms: '',
        address: '',
        recruitment: '',
        jobs: '',
        card_number:'',
        code:'',
        bank_name:'',
      },
      rules: {
        agents_name: [requiredRules('代理商姓名')],
        phone: requiredRules('手机号'),
        regionids: [requiredRules('所在省市区', 'change')],
        address: [requiredRules('详细地址')],
        terms: [requiredRules('代理商入驻费'),{validator:this.validMoney}],
        recruitment: requiredRules('招募人'),
        jobs: requiredRules('工号'),
        card_number: requiredRules('银行卡号'),
        code: requiredRules('银行卡所属银行','change'),
      },
      isSub:false,
    }
  },
  mounted() {
    this.getAreaList()
    this.init()
  },
  methods: {
    async init() {
      const { type, agentId } = this.$route.query
      if (type == 'edit' || type == 'detail') {
        let action = 'edit'
        if (type == 'detail') {
          this.disabled = true
          action = 'detail'
        }
        const result = await getTheAgent({ action }, agentId)
        this.resultHandler(result)
      }
    },
    resultHandler(result) {
      const {
        address,
        agent_id,
        agents_name,
        area,
        city,
        jobs,
        created,
        phone,
        province,
        recruitment,
        regionids,
        regions,
        terms,
        card_number,
        code,
        bank_name,

      } = result.data.data
      this.form = {
        address,
        agent_id,
        agents_name,
        area,
        city,
        jobs,
        created,
        phone,
        regions: [province, city, area],
        province,
        recruitment,
        regionids: JSON.parse(regionids),
        terms:isNaN(terms / 100) ? '' : terms / 100,
        card_number,
        code,
        bank_name,
      }
    },
    regionChange(value) {
      console.log(value)
      var vals = this.getCascaderObj(value, this.AreaJson)
      if (vals.length > 0) {
        this.form.regions = [vals[0].label, vals[1].label, vals[2].label]
      } else {
        this.form.regions = []
      }
      console.log(this.form.regions)
    },
    getCascaderObj(val, opt) {
      return val.map(function (value, index, array) {
        for (var itm of opt) {
          if (itm.value === value) {
            opt = itm.children
            return itm
          }
        }
        return null
      })
    },

    async getAreaList() {
      const result = await getArea()
      this.AreaJson = result.data.data
    },
    validMoney(rule,value,callback){
      // console.log('validMoney',value)
      if(isNaN(value) || value<0){
        callback(new Error('请输入正确的金额'))
      }
      else{
        callback()
      }
    },
    submitFn(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { type, agentId } = this.$route.query
          let subData = {
            ...this.form,
          }
          subData.regionids = JSON.stringify(subData.regionids)
          subData.province = subData.regions[0]
          subData.city = subData.regions[1]
          subData.area = subData.regions[2]
          subData.regions = JSON.stringify(subData.regions)
          subData.terms = Math.round((subData.terms || 0) * 100)
          this.isSub = true;
          try{
            if (type == 'add') {
              const result = await addTheAgent(subData, type == 'edit' ? agentId : null)
              this.$message.success('保存成功')
              this.isEditCheckBox = true
              this.$router.go(-1)
            } else {
              const result = await updateTheAgent(subData)
              this.$message.success('修改成功')
              this.isEditCheckBox = true
              this.$router.go(-1)
            }
          }catch(e){
            this.isSub = false;
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 银行 start
    
    // 结算所属银行
    async querySearch(queryString, cb) {
      this.AllBank = await this.$api.adapay.getBank({
        bank_name: queryString
      })
      var restaurants = this.AllBank.map((item) => {
        return {
          value: item.bank_name,
          bank_code: item.bank_code,
          id: item.id
        }
      })
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      //调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    handleSelectBank(val) {
      console.log(val)
      this.form.code = val.bank_code
      this.form.bank_name = val.value
    },
    // 银行 end
  },

  goback() {
    this.$router.back(-1)
  },
  beforeRouteLeave(to, from, next) {
    const { type } = this.$route.query
    console.log(to, type)
    if ((type == 'add' && !this.isEditCheckBox) || (type == 'edit' && !this.isEditCheckBox)) {
      this.$confirm('确定要离开当前页面，您将丢失已编辑的数据？！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then((res) => {
          next()
        })
        .catch(() => {
          next(false)
        })
    } else {
      next()
    }
  }
}
</script>

<style>
</style>